from datetime import datetime

from flask import Blueprint, render_template, request, jsonify, session
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_login import login_required

from sqlalchemy import and_, schema

from werkzeug.security import generate_password_hash

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.utils.http import success_api, goods_api, carts_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.exts.redis_command import getttl
from applications.models import Carts
from applications.schemas import CartsOutSchema
from applications.common.utils import upload as upload_curd

wxcarts = Blueprint('wxcarts', __name__, url_prefix='/wxcarts')
# 加入微信购物车

@wxcarts.route('/wxcartsadd', methods=["POST", "PUT"])
def wxcartsadd():
    # {'openid': '55_rXi_eH_kLLXQvYmGrt-drAt_guhBS1L_-XCJAZvk50td6MbUvlv4WSAJboJxqAx29E_Zo1Z4nmY037Y9MI4PtJkC7svfSgIZF9VZofIRKccBAlu4RBcHoQA2Hvns88XrrtPAU7TiN5laLisHRTSaAIADFE', 'subOrders': [{'id': 2, 'image': 'http://127.0.0.1:5000/static/upload/goods/002226dd-97ba-4fd5-85ba-6228e20e9815.jpg', 'index': 0, 'name': '1', 'price': 1,
    # 'cup': '大杯', 'ico': '去冰', 'sugar': '七分糖', 'dosing': '布丁', 'nums': 1}]}

    req_json = request.json

    print('req_json:', req_json)
    tokens = xss_escape(req_json.get('token'))
    openid = xss_escape(req_json.get('openid'))

    subOrders = req_json.get('subOrders')

    # print('openid:', openid)

    print('item:', subOrders)
    carts = Carts()
    carts.openid = openid
    carts.gid = subOrders.get('gid')
    carts.good_price = subOrders.get('price')
    carts.good_gname = subOrders.get('name')
    carts.good_photo = subOrders.get('image')
    carts.number = subOrders.get('nums')
    carts.is_del = 0
    carts_dict = carts.to_dict()

    # 存redis
    cache.set(r'wxcartsadd', carts_dict, timeout=900)

    # 创建反序列化对象
    # schema = CartsOutSchema()
    # cart = schema.load(carts_dict)
    # print(type(result))

    # 存mysql
    cart=cache.get('wxcartsadd')
    print('cart:',cart)
    c=Carts()
    c.gid=cart.get('gid')
    c.openid = cart.get('openid')
    c.good_price = cart.get('good_price')
    c.good_gname = cart.get('good_gname')
    c.good_photo = cart.get('good_photo')
    c.number = cart.get('number')
    c.is_del = 0
    db.session.add(c)
    db.session.commit()

    # data_message = schema.dump(data, many=True)  # 对数据进行序列化，多条数据加many=True

    # print(req_json)

    return goods_api(msg='添加成功!')


# 微信购物车列表

@wxcarts.route('/wxcartslist', methods=["POST", "GET"])
@jwt_required()
def wxcartslist():
    # print('res:',request.headers)
    # username = get_jwt_identity()
    # print('username:',username)
    flag=0
    # cache.set('ket', 1)
    req_json = request.json
    openids = req_json.get('openid')
    openid = cache.get('openid') or openids
    token = cache.get('token')

    ordercount = cache.get('ordercount')
    cartslist = cache.get('cartslist')


    if ordercount and cartslist:
        res = Carts.query.filter(and_(Carts.openid == openid, Carts.is_del == 0)).count()
        redis_count = len(cartslist)
    # 判断redis里面的数据和数据库里面的是不是相等，相等就获取redis，就读去redis，否则同步mysql
        if redis_count!=res:
            flag=1
    else:
        flag=1
    # print('redis_count:',redis_count)
    # print('res:',res)
    # 先从缓存中查看，有就从缓存里面获取，没有就从数据库里面查询，在更新到混存里面，下一次就从混存里面查询
    if ordercount and cartslist and flag==0:
        # print('cartslist', cartslist)
        print('redis')

        # 创建反序列化对象
        schema = CartsOutSchema()
        result = schema.load(cartslist[0])
        # print(type(result))

        return carts_api(subOrders=cartslist, ordercount=ordercount, msg='查询成功！')

    if flag==1:
        print('mysql')
        # print(type(openid), token)

        # req_json = request.is_json
        # reqjson = request.json
        # print(req_json)
        # openid = xss_escape(req_json.get('openid'))
        # print(openid)
        #     from marshmallow import Schema, fields, post_load

        # from SQLconfig.models import *
        subOrders = Carts.query.filter(and_(Carts.openid == openid, Carts.is_del == 0)).all()
        ordercount = {}
        num = 0
        money = 0.00
        if subOrders:
            for item in subOrders:
                # print('item.number:', item.number)
                num = num + item.number
                money = money + float(item.good_price) * int(item.number)
        ordercount['num'] = num
        ordercount['money'] = money

        # print('ordercount:', ordercount)

        cartslist = model_to_dicts(CartsOutSchema, data=subOrders)


        cache.set(f'cartslist', cartslist, timeout=900)
        cache.set(f'ordercount', ordercount, timeout=900)
        # print('cartslist:',cartslist)

        # for item in cartslist:
        #     print('item[number]:', item['good_price'])
        #     # print(item['number'])
        #     # sum += int(item.get('number'))
        #     # money += int(item.get('good_price'))
        #     sum = sum + item['number']
        #     money = money + item['good_price']
        #
        # ordercount = {
        #     'sum': sum,
        #     'money': money
        # }
        # carts_api(errno: int = 0, subOrders = None, ordercount = None, msg: str = ''):
        # return success_api()
        return carts_api(subOrders=cartslist, ordercount=ordercount, msg='查询成功！')
    print(1)
    return carts_api(errno=1,msg='失败')


# 微信购物车加一
@jwt_required()
@wxcarts.route('/wxcartsjia', methods=["POST", "GET"])
def wxcartsjia():
    f=0
    req_json = request.json
    # print(req_json)
    id = req_json.get('id')

    ordercount = cache.get('ordercount')
    cartslist = cache.get('cartslist')
    # ttl = getttl('cartslist')
    # print('ttl', type(ttl))

    # redis
    num=0
    money=0.00
    if ordercount and cartslist:
        print('redis')
        for cart in cartslist:
            # print('cart:', cart)
            if cart.get('id') == id:
                if cart['number']<50:
                    cart['number'] = cart.get('number') + 1
                    num=cart['number']
                    money = ordercount['money'] + float(cart.get('good_price')) * int(cart.get('number'))
                    f=0
                else:
                    cart['number'] = cart.get('number')
                    num = cart['number']
                    money = ordercount['money'] + float(cart.get('good_price')) * int(cart.get('number'))
                    f=1
        ordercount['num'] = num
        ordercount['money'] = money
        cache.set(f'cartslist', cartslist, timeout=900)
        cache.set(f'ordercount', ordercount, timeout=900)
        # print('cartslist:', cartslist)
        # return success_api()
    #     操作数据库
    if f==0:
        cart = Carts.query.get(id)
        if cart:
            cart.number = cart.number + 1
            db.session.commit()
        return success_api()
    else:
        return fail_api(msg='单次限购50杯')
        # mysql
    # else:
    #     print('mysql')
    #     cart = Carts.query.get(id)
    #     if cart:
    #         cart.number = cart.number + 1
    #         db.session.commit()
    #
    #     return success_api()
    #


# 微信购物车减一
@jwt_required()
@wxcarts.route('/wxcartssub', methods=["POST", "GET"])
def wxcartssub():
    req_json = request.json
    # print(req_json)
    id = req_json.get('id')

    # print(id)
    # id = xss_escape(req_json.get('id'))

    ordercount = cache.get('ordercount')
    cartslist = cache.get('cartslist')
    # redis
    num = 0
    money = 0.00
    if ordercount and cartslist:
        print('redis')
        for cart in cartslist:
            # print('cart:', cart)
            if cart.get('id') == id:
                if cart['number'] <= 1:
                    cartslist.pop()
                else:
                    cart['number'] = cart.get('number') - 1
                    num = cart['number']
                    money = ordercount['money'] + float(cart.get('good_price')) * int(cart.get('number'))
        ordercount['num'] = num
        ordercount['money'] = money
        cache.set(f'cartslist', cartslist, timeout=900)
        cache.set(f'ordercount', ordercount, timeout=900)
        # print('cartslistewewe:', cartslist)
        # return success_api()
    # mysql
    # else:
    #     print('mysql')
    # 操作数据库
    cart = Carts.query.get(id)
    if cart:
        if cart.number <= 1:
            db.session.delete(cart)
            db.session.commit()
        else:
            cart.number = cart.number - 1
            db.session.commit()
    return success_api()


# 删除购物车
@jwt_required()
@wxcarts.route('/delcarts', methods=["POST", "GET"])
def delcarts():
    req_json = request.json
    # print(req_json)
    id = req_json.get('id')
    # id = xss_escape(req_json.get('id'))
    # openid=cache.get('openid')
    cart = Carts.query.get(id)
    msg = 0
    if cart:
        try:
            cart.is_del = 1
            db.session.commit()
            msg = 0
        except Exception as e:
            msg = 1
            print(e)
            db.session.rollback()
    return carts_api(errno=msg, msg='删除成功')
